package com.example.demo.service.impl;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.constant.SourceName;
import com.example.demo.dao.UserMapper;
import com.example.demo.config.datasourseconfig.DataSource;
import com.example.demo.pojo.User;
import com.example.demo.pojo.UserDTO;
import com.example.demo.pojo.UserIdDTO;
import com.example.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDateTime;

/**
* @author 12
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-04-01 17:53:37
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public User getUserById(String id) {
        User user = userMapper.selectById(id);
        return user;
    }

    @Override
    @DataSource(SourceName.write)
//    @DS(value = "write")
    @Transactional(rollbackFor = Exception.class)
    public int createUser(UserDTO dto) {
        User user = JSON.parseObject(JSON.toJSONString(dto), User.class);
        return userMapper.insert(user);
    }

    @Override
    @DataSource(SourceName.write)
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(UserDTO dto) {
        User user = JSON.parseObject(JSON.toJSONString(dto), User.class);
        return userMapper.updateById(user);
    }

    @Override
    @DataSource(SourceName.write)
    @Transactional(rollbackFor = Exception.class)
    public int deleteUser(UserIdDTO dto) {
        User user = User.builder()
                .id(dto.getId())
                .deleted("01")
                .build();
        return userMapper.updateById(user);
    }

    @Override
    public User getUserByUsername(String username) {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class)
                .eq(User::getUsername, username);
        return userMapper.selectOne(wrapper);
    }


//    @Override
//    @Transactional(rollbackFor = RuntimeException.class)
//    public String uploadConfig(ProcessNodeParamVO vo, MultipartFile file) {
//
//        String downloadUrl = null;
//        String fileContent = null;
//
//        ToolProcessVertexEntity entity = new ToolProcessVertexEntity();
//        entity.setProcessId(vo.getProcessId());
//        entity.setVersionId(vo.getVersionId());
//        entity.setNodeId(vo.getNodeId());
//
//
//        if (ObjectUtil.isNotEmpty(file)) {
//
//            if (!"json".equals(FileUtil.getSuffix(file.getOriginalFilename()))) {
//                throw ServiceExceptionUtil.exception(GlobalCode.BAD_REQUEST, "请确认配置文件格式为json");
//            }
//
//            //上传文件至阿里云
//            downloadUrl = uploadFile(file);
//            fileContent = getFileContent(file);
//
//            entity.setConfig(fileContent);
//            entity.setConfigFile(downloadUrl);
//            entity.setConfigUpdateTime(LocalDateTime.now());
//        } else {
//            //删除文件
//            if (StringUtils.isEmpty(vo.getFileUrl())) {
//                entity.setConfig(fileContent);
//                entity.setConfigFile(downloadUrl);
//                entity.setConfigUpdateTime(null);
//            }
//        }
//
//        toolProcessVertexMapper.updateProcessVertex(entity);
//        return downloadUrl;
//    }

    private String getFileContent(MultipartFile file) {

        try {

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(file.getInputStream()));

            // 读取文件内容
            String line;
            StringBuilder contentBuilder = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                contentBuilder.append(line);
            }

            log.info("文件内容：" + StrUtil.cleanBlank(contentBuilder));

            bufferedReader.close();
            return StrUtil.cleanBlank(contentBuilder);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


/**
 * 拦截器分页（
 */
//    IPage<ToolFormatVO> formatPage = toolFormatMapper.pageList(new Page<>(pageParam.getCurrentPage(), pageParam.getPageSize()), param);
}




